package cn.net.ecode.modules.sys.fileupload.web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.mapper.JsonMapper;
import cn.net.ecode.common.utils.Encodes;
import cn.net.ecode.common.utils.IdGen;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.sys.fileupload.AjaxFileUploadUtil;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 文件上传
 * 
 * @author 刘保全
 * 
 */
@Controller
public class FileUploadController extends BaseController {

	/**
	 * 文件上传service
	 */
	@RequestMapping(value = "fileupload")
	@ResponseBody
	public String fileupload(MultipartHttpServletRequest multipartRequest)
			throws Exception {

		AjaxFileUploadUtil.init();

		String message = "上传成功";
		String result = "true";
		List<Map<String, Object>> list = Lists.newArrayList();

		// 获取多个file
		for (Iterator<String> it = multipartRequest.getFileNames(); it
				.hasNext();) {
			String key = it.next();
			MultipartFile multipartFile = multipartRequest.getFile(key);
			String fileName = multipartFile.getOriginalFilename(); // 文件名
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); // 文件后缀

			if (StringUtils.isNotBlank(fileName)) {
				if (!AjaxFileUploadUtil.suffixs.contains(suffix)) {
					message = "只支持" + AjaxFileUploadUtil.suffixMsg + "类型的文件！";
					result = "false";
					break;
				}
				if (multipartFile.getSize() > AjaxFileUploadUtil.sizeMax) {
					message = "文件大小最大为" + AjaxFileUploadUtil.sizeMax;
					result = "false";
					break;
				}

				String fieldName = multipartFile.getName();
				String guid = IdGen.nextId();
				String pathname = AjaxFileUploadUtil.getDataFileName(guid,
						fileName);
				InputStream in = multipartFile.getInputStream();
				FileOutputStream out = new FileOutputStream(pathname);
				StreamUtils.copy(in, out);
				in.close();
				out.close();

				Map<String, Object> map = Maps.newHashMap();
				map.put("fieldName", fieldName);
				map.put("guid", guid);
				map.put("fileName", fileName);
				map.put("pathname", pathname);
				map.put("size", multipartFile.getSize());
				map.put("suffix", suffix);

				list.add(map);

			}

		}

		if (list.size() == 0 && result.equals("true")) {
			result = "false";
			message = "请选择上传文件";
		}

		Map<String, Object> messageMap = Maps.newHashMap();
		messageMap.put("list", list);
		messageMap.put("message", message);
		messageMap.put("result", result);

		String msg = JsonMapper.toJsonString(messageMap);
		logger.debug("fileupload msg:" + msg);
		return msg;
	}

	/**
	 * 下载
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException 
	 */
	@RequestMapping(value = "filedownload")
	public void filedownload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		String filePath = request.getParameter("filepath");
		String fileName = request.getParameter("fileName");
		
		// WebOffice点聚中间件 http://www.dianju.cn/products/middleware/weboffice
		String docType = null;
		if (StringUtils.endsWithAny(filePath, ".doc", ".docx")){
			docType = "doc";
		}else if (StringUtils.endsWithAny(filePath, ".xls", ".xlsx")){
			docType = "xls";
		}else if (StringUtils.endsWithAny(filePath, ".ppt", ".pptx")){
			docType = "ppt";
		}else if (StringUtils.endsWithAny(filePath, ".wps", ".wpt")){
			docType = "wps";
		}else if (StringUtils.endsWithAny(filePath, ".pdf")){
			docType = "pdf";
		}
		if (docType != null){
			request.setAttribute("docType", docType);
			request.getRequestDispatcher("/static/weboffice/preview.jsp").forward(request, response);
			return;
		}
		if (StringUtils.endsWithAny(filePath, ".download")){
			filePath = filePath.replaceFirst(".download", "");
		}

		// 下载文件
		response.reset();
		response.setHeader("Content-Type", "application/octet-stream");
		response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode(fileName));
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			File file = new File(filePath);
			if (!file.exists()) {
				return;
			}
			FileUtils.copyFile(file, os);
		} finally {
			if (os != null) {
				os.close();
			}
		}

	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "filedelete")
	@ResponseBody
	public String filedelete(HttpServletRequest request,
			HttpServletResponse response) {
		String filepath = request.getParameter("filepath");
		try {
			File file = new File(filepath);
			if (file.exists()) {
				boolean ok = file.delete();
				if (ok) {
					return renderResult(Global.TRUE, "删除成功!");
				} else {
					return renderResult(Global.FALSE, "删除失败!");
				}
			} else {
				return renderResult(Global.FALSE, "文件不存在");
			}
		} catch (Exception e) {
			return renderResult(Global.FALSE, "删除失败!");
		}
	}

}
